<template>
	<view class="payment-container">
		<!-- 订单基本信息 -->
		<view class="order-info-section">
			<view class="store-info">
				<image src="/static/member/store-icon.png" class="store-icon" mode="aspectFit"></image>
				<text class="store-name">{{ storeInfo.name }}</text>
			</view>
			<!-- 外卖地址信息 -->
			<view class="delivery-address" v-if="orderInfo.mode === 'takeout'">
				<view class="address-header">
					<text class="address-title">收货地址</text>
					<text class="change-address" @click="showAddressSelector = true">更换地址</text>
				</view>
				<view class="address-content" v-if="selectedAddress">
					<view class="address-info">
						<text class="contact">{{ selectedAddress.contacts }} {{ selectedAddress.contactsPhone }}</text>
						<text class="address">{{ selectedAddress.province }}{{ selectedAddress.city }}{{ selectedAddress.district }}{{ selectedAddress.street }}{{ selectedAddress.detail }}</text>
					</view>
				</view>
				<view class="no-address" v-else @click="showAddressSelector = true">
					<text>请选择收货地址</text>
					<text class="arrow">></text>
				</view>
			</view>
		</view>

		<!-- 菜品信息 -->
		<view class="food-items-section">
			<view class="section-header">
				<text class="section-title">菜品信息</text>
				<text class="item-count">共{{ cartItems.length }}件</text>
			</view>
			<view class="food-list">
				<view class="food-item" v-for="(item, index) in displayedItems" :key="index">
					<image :src="`https://rsl-plus.oss-rg-china-mainland.aliyuncs.com/${item.dishImage}`" class="food-image" mode="aspectFill"></image>
					<view class="food-info">
						<text class="food-name">{{ item.dishName }}</text>
						<text class="food-spec" v-if="item.specs">{{ item.specs }}</text>
						<text class="food-remark" v-if="item.remark">{{ item.remark }}</text>
						<view class="food-price-quantity">
							<text class="food-price">￥{{ formatAmount(item.price) }}</text>
							<text class="food-quantity">x{{ item.quantity }}</text>
						</view>
					</view>
				</view>
			</view>
			<!-- 展开/收起按钮 -->
			<view class="expand-section" v-if="cartItems.length > 2" @click="isExpanded = !isExpanded">
				<text class="expand-text">{{ isExpanded ? '收起' : `展开剩余${remainingItems}件` }}</text>
				<text class="expand-icon" :class="{ 'expanded': isExpanded }">></text>
			</view>
		</view>

		<!-- 优惠券模块 -->
		<view class="coupon-section" v-if="!orderId" @click="selectCoupon">
			<view class="section-header">
				<text class="section-title">优惠券</text>
				<text class="coupon-tip">{{ selectedCoupon ? `已选：${selectedCoupon.name}` : '请选择优惠券' }}</text>
			</view>
			<view class="selected-coupon" v-if="selectedCoupon">
				<text class="coupon-name">{{ selectedCoupon.name }}</text>
				<text class="coupon-amount">-￥{{ formatAmount(selectedCoupon.amount) }}</text>
			</view>
		</view>

		<!-- 订单备注 -->
		<view class="remark-section" v-if="!orderId">
			<view class="section-header">
				<text class="section-title">订单备注</text>
				<text class="remark-tip">选填</text>
			</view>
			<textarea 
				class="remark-input" 
				v-model="orderRemark" 
				placeholder="请输入订单备注信息（如：不要辣、少放盐等）"
				maxlength="100"
			></textarea>
		</view>

		<!-- 金额信息 -->
		<view class="amount-section">
			<view class="amount-item">
				<text>商品金额</text>
				<text>￥{{ formatAmount(totalAmount) }}</text>
			</view>
			<view class="amount-item" v-if="orderInfo.mode === 'takeout'">
				<text>配送费</text>
				<text>￥{{ formatAmount(deliveryFee) }}</text>
			</view>
			<view class="amount-item" v-if="orderInfo.mode === 'takeout'">
				<text>打包费</text>
				<text>￥{{ formatAmount(packagingFee) }}</text>
			</view>
			<view class="amount-item" v-if="selectedCoupon">
				<text>优惠金额</text>
				<text class="discount">-￥{{ formatAmount(selectedCoupon.amount) }}</text>
			</view>
			<view class="amount-item total">
				<text>应付金额</text>
				<text class="final-amount">￥{{ formatAmount(finalAmount) }}</text>
			</view>
		</view>

		<!-- 底部支付按钮 -->
		<view class="payment-footer">
			<view class="total-info">
				<text class="total-label">合计：</text>
				<text class="price">￥{{ formatAmount(finalAmount) }}</text>
			</view>
			<button class="pay-button" @click="initiatePaymentProcess">{{ orderInfo.mode === 'scan' ? '确认提交' : '立即支付' }}</button>
		</view>

		<!-- 优惠券选择弹窗 -->
		<view v-if="showCouponPopup" class="coupon-popup">
			<view class="popup-mask" @click="showCouponPopup = false"></view>
			<view class="popup-content">
				<view class="popup-header">
					<text class="popup-title">我的优惠券</text>
					<text class="close-icon" @click="showCouponPopup = false">×</text>
				</view>
				<view class="coupon-list" v-if="couponList.length > 0">
					<view
						class="coupon-item"
						v-for="coupon in couponList"
						:key="coupon.couponId"
						:class="{ 'disabled': coupon.couponStatus !== 0 || (coupon.couponType === '1' && !isCouponUsable(coupon)) }"
					>
						<view class="coupon-info">
							<text class="coupon-name">{{ coupon.couponName }}</text>
							<text class="coupon-desc">{{ coupon.couponDescribe }}</text>
							<text class="coupon-term">有效期至{{ coupon.deadlineTime }}</text>
						</view>
						<view class="coupon-action">
							<text class="coupon-amount">{{ getCouponDisplayAmount(coupon) }}</text>
							<button
								class="use-btn"
								:class="{ 'btn-disabled': coupon.couponStatus !== 0 || (coupon.couponType === '1' && !isCouponUsable(coupon)) }"
								:disabled="coupon.couponStatus !== 0 || (coupon.couponType === '1' && !isCouponUsable(coupon))"
								@click="isCouponUsable(coupon) && chooseCoupon(coupon)"
							>使用</button>
						</view>
					</view>
				</view>
				<view class="coupon-list" v-else>
					<view class="empty-coupon">
						<text class="empty-text">暂无优惠券</text>
					</view>
				</view>
			</view>
		</view>

		<!-- 地址选择器组件 -->
		<AddressSelector
			v-model:show="showAddressSelector"
			@select="handleAddressSelect"
		/>

		<!-- 支付方式选择弹窗 -->
		<view v-if="paymentMethodPopupVisible" class="modal">
		  <view class="modal-mask" @tap="closePaymentMethodPopup"></view>
		  <view class="payment-popup-wrapper">
			<view class="payment-method-popup" :animation="popupAnimation">
			  <view class="popup-header">
				<text class="close-btn" @tap="closePaymentMethodPopup">×</text>
				<text class="title">选择支付方式</text>
			  </view>
			  <view class="method-list">
				<view class="method-item" @tap="selectPaymentMethod('wechat')">
				  <image src="/static/tabbar/微信支付.png" class="method-icon wechat-icon"></image>
				  <view class="method-info">
					<text class="method-name">微信支付</text>
					<text class="method-desc">推荐使用微信支付</text>
				  </view>
				  <text class="checkmark">✔</text>
				</view>
				<view class="method-item" @tap="selectPaymentMethod('member')">
				  <image src="/static/tabbar/会员卡.png" class="method-icon member-icon"></image>
				  <view class="method-info">
					<text class="method-name">会员卡支付</text>
					<text class="method-desc">使用会员卡余额支付</text>
				  </view>
				  <text class="checkmark">✔</text>
				</view>
			  </view>
			</view>
		  </view>
		</view>

		<!-- 会员卡支付提示弹窗 -->
		<view v-if="memberCardPopupVisible" class="modal">
		  <view class="modal-mask" @tap="closeMemberCardPopup"></view>
		  <view class="payment-popup-wrapper">
			<view class="member-card-popup" :animation="popupAnimation">
			  <view class="popup-header">
				<text class="close-btn" @tap="closeMemberCardPopup">×</text>
				<text class="title">会员卡支付</text>
			  </view>
			  <view class="popup-content">
				<image src="/static/tabbar/会员卡.png" class="card-icon"></image>
				<view class="amount-info">
				  <text class="amount-label">支付金额</text>
				  <view class="amount-row">
					<text class="currency">¥</text>
					<text class="amount">{{ formatAmount(finalAmount) }}</text>
				  </view>
				</view>
			  </view>
			  <view class="popup-footer">
				<button class="confirm-btn" @tap="confirmMemberCardPayment">立即支付</button>
			  </view>
			</view>
		  </view>
		</view>

		<!-- 支付选择弹窗 -->
		<view v-if="paymentPopupVisible" class="modal">
		  <view class="modal-mask" @tap="closePaymentPopup"></view>
		  <view class="payment-popup-wrapper">
			<view class="payment-popup" :animation="popupAnimation">
			  <view class="popup-header">
				<text class="close-btn" @click="closePaymentPopup">×</text>
				<text class="password-btn">使用密码</text>
			  </view>
			  <view class="amount-section">
				<text class="merchant-name">商家名称</text>
				<view class="currency-amount-wrapper">
				  <text class="currency">¥</text>
				  <text class="amount">{{ formatAmount(finalAmount) }}</text>
				</view>
			  </view>
			  <view class="divider-line"></view>
			  <view class="payment-method-section">
				<view class="method-header">
				  <view class="label">付款方式</view>
				  <view class="change-method">
					<text>更改</text>
					<text class="arrow">></text>
				  </view>
				</view>
				<view class="method-item">
				  <image src="/static/tabbar/零钱通.png" class="method-icon"></image>
				  <view class="method-details">
					<text class="method-name">零钱通</text>
					<text class="method-provider">由腾安公司提供货币基金销售服务</text>
				  </view>
				  <text class="checkmark">✔</text>
				</view>
			  </view>
			  <view class="popup-footer">
				<button class="pay-btn" @click="confirmPayment">支付</button>
			  </view>
			</view>
		  </view>
		</view>

		<!-- 密码输入弹窗 -->
		<view v-if="passwordPopupVisible" class="modal">
		  <view class="modal-mask" @tap="closePayPasswordPopup"></view>
		  <view class="payment-popup-wrapper">
			<view class="pay-password-popup" :animation="popupAnimation">
			  <view class="popup-header">
				<text class="close-btn" @tap="closePayPasswordPopup">×</text>
				<text class="face-btn">使用面容</text>
			  </view>
			  <view class="popup-amount">
				<text class="merchant">商家名称</text>
				<view class="currency-amount-row">
				  <text class="currency">¥</text>
				  <text class="amount">{{ formatAmount(finalAmount) }}</text>
				</view>
			  </view>
			  <view class="popup-method">
				<view class="method-label">付款方式</view>
				<view class="method-change">
				  <text>更改</text>
				  <text class="arrow">></text>
				</view>
				<view class="method-item">
				  <image src="/static/tabbar/建设银行.png" class="method-icon"></image>
				  <view class="method-info">
					<text class="method-name">建设银行储蓄卡</text>
					<text class="method-desc">**** **** **** 2779</text>
				  </view>
				  <text class="checkmark">✔</text>
				</view>
			  </view>
			  <view class="popup-password">
				<view class="password-box">
				  <view v-for="(cell, index) in 6" :key="index" class="pwd-cell">
					<view v-if="password.length > index" class="dot"></view>
				  </view>
				</view>
			  </view>
			  <view class="popup-keyboard">
				<view v-for="(row, rowIndex) in keyboardRows" :key="rowIndex" class="keyboard-row">
				  <view v-for="(key, keyIndex) in row" :key="keyIndex" :class="['key-btn', key === 'del' ? 'del' : (key === '' ? 'empty' : '')]" @click="onKeyClick(key)">{{ key }}</view>
				</view>
			  </view>
			</view>
		  </view>
		</view>

		<!-- 支付成功弹窗 -->
		<view v-if="successPopupVisible" class="modal">
		  <view class="modal-mask" @tap="closePaySuccessPopup"></view>
		  <view class="payment-popup-wrapper">
			<view class="pay-success-popup" :animation="popupAnimation">
			  <view class="success-top-bar">
				<image src="/static/tabbar/微信支付.png" class="success-icon"></image>
				<text class="success-text">支付成功</text>
			  </view>
			  <view class="success-amount-block">
				<text class="success-merchant">商家名称</text>
				<view class="success-amount-row">
				  <text class="currency">¥</text>
				  <text class="amount">{{ formatAmount(finalAmount) }}</text>
				</view>
			  </view>
			  <view class="success-bottom-block">
				<button class="success-btn" @tap="closePaySuccessPopup">完成</button>
			  </view>
			</view>
		  </view>
		</view>
	</view>
</template>

<script setup>
import { ref, computed, onMounted, nextTick } from 'vue'
import { onUnload } from '@dcloudio/uni-app'
import { useOrderStore } from '../../store/order'
import { couponApi, orderApi, payHistoryApi, userApi, customerApi, dishApi } from '../../api/index'
import AddressSelector from '../../components/AddressSelector.vue'

/**
 * 订单支付页面
 * 支持两种模式：
 * 1. 正常下单流程：不传入orderId，使用store中的数据
 * 2. 查看已有订单：传入orderId，显示对应订单的数据
 */
const orderId = ref(null)

const orderStore = useOrderStore()

/**
 * 店铺信息
 */
const storeInfo = computed(() => orderStore.storeInfo)

/**
 * 订单基本信息
 */
const orderInfo = computed(() => orderStore.orderInfo)

/**
 * 购物车商品列表
 */
const cartItems = computed(() => orderStore.cartItems)

/**
 * 
 * 收货地址信息
 */
const selectedAddress = computed(() => orderStore.selectedAddress)

/**
 * 优惠券信息
 */
const selectedCoupon = computed(() => {
	console.log("selectedCoupon:", orderStore.selectedCoupon)
	return orderStore.selectedCoupon
})

/**
 * 订单备注
 */
const orderRemark = computed({
	get: () => orderStore.orderRemark,
	set: (value) => orderStore.setOrderRemark(value)
})

/**
 * 控制菜品列表展开/收起
 */
const isExpanded = ref(false)
const displayedItems = computed(() => {
	return isExpanded.value ? cartItems.value : cartItems.value.slice(0, 2)
})

/**
 * 计算剩余未显示的菜品数量
 */
const remainingItems = computed(() => {
	return cartItems.value.length - 2
})

/**
 * 订单总金额
 */
const totalAmount = computed(() => orderStore.totalAmount)

/**
 * 订单实付金额
 */
const finalAmount = computed(() => {
	let amount = totalAmount.value
	if (orderInfo.value.mode === 'takeout') {
		amount += deliveryFee.value + packagingFee.value
	}
	if (selectedCoupon.value) {
		amount -= selectedCoupon.value.amount
	}
	return Number(amount.toFixed(2))
})

// 配送费和打包费
const deliveryFee = ref(5) // 配送费
const packagingFee = ref(2) // 打包费

// 地址选择器显示状态
const showAddressSelector = ref(false)

// 处理地址选择
const handleAddressSelect = (address) => {
	showAddressSelector.value = false
}

// 选择优惠券
const couponList = ref([])
const token = uni.getStorageSync('token')
// 预留接口
const getCouponList = async () => {
	const res = await couponApi.getCouponListByUserId(token)
	couponList.value = res.data
}

// 判断满减券是否可用
const isCouponUsable = (coupon) => {
	if (coupon.couponType === "1") {
		return totalAmount.value >= coupon.minAmount
	}
	return true
}

// 金额显示
const getCouponDisplayAmount = (coupon) => {
	if (coupon.couponType === "0") {
		// 如果 discount >= 1，显示为 "X折"；如果 < 1，显示为 "X折"
		let discountDisplay = coupon.discount
		if (coupon.discount >= 1) {
			discountDisplay = coupon.discount
		} else {
			discountDisplay = coupon.discount * 10
		}
		return `${discountDisplay}折`
	}
	if (coupon.couponType === "1" || coupon.couponType === "2") return `￥${formatAmount(coupon.reduceAmount)}`
	return ''
}

const showCouponPopup = ref(false)
const selectCoupon = () => {
	showCouponPopup.value = true
	getCouponList()
}
const chooseCoupon = (coupon) => {
	const amount = calculateCouponAmount(coupon)
	orderStore.setSelectedCoupon({
		id: coupon.couponId,
		name: coupon.couponName,
		amount: amount,
		type: coupon.couponType,
		description: coupon.couponDescribe
	})
	showCouponPopup.value = false
}

const calculateCouponAmount = (coupon) => {
	console.log("coupon:", coupon)
	let amount = 0
	if (coupon.couponType === "0") { // 折扣券
		// 如果 discount 是 8 表示 8 折，如果是 0.8 表示 0.8 折
		// 统一处理：如果 discount >= 1，按折扣数处理；如果 < 1，按折扣率处理
		let discountRate = coupon.discount
		if (coupon.discount >= 1) {
			discountRate = coupon.discount / 10 // 8 折 = 0.8
		}
		amount = totalAmount.value * (1 - discountRate)
	} else if (coupon.couponType === "1") { // 满减券
		amount = totalAmount.value >= coupon.minAmount ? coupon.reduceAmount : 0
	} else if (coupon.couponType === "2") { // 立减券
		amount = coupon.reduceAmount
	}
	return Number(amount.toFixed(2))
}

// 处理支付
const handlePayment = async () => {
	try {
		// 构建订单数据
		const orderData = {
			totalAmount: totalAmount.value,
			discountAmount: selectedCoupon.value?.amount || 0,
			payableAmount: finalAmount.value,
			orderType: 2, // 默认为外卖订单
			remark: orderRemark.value || "",
			shippingAddress: orderInfo.value.mode === 'takeout' ? 
				`${selectedAddress.value?.province}${selectedAddress.value?.city}${selectedAddress.value?.district}${selectedAddress.value?.street}${selectedAddress.value?.detail}` : "",
			uId: token
		}
		
		console.log("创建订单数据:", orderData)
		const res = await orderApi.createOrder(orderData)
		
		if (res.code !== 200) {
			throw new Error(res.msg || '创建订单失败')
		}
		
		// 保存订单编号到本地存储
		uni.setStorageSync('orderId', res.data)
		
		// 显示支付方式选择弹窗
		paymentMethodPopupVisible.value = true
		// 执行滑入动画
		nextTick(() => {
			animation.value.translateY(0).step()
			popupAnimation.value = animation.value.export()
			checkPopupStatus()
		})
		
	} catch (error) {
		console.error('创建订单失败:', error)
		uni.showToast({
			title: error.message || '创建订单失败',
			icon: 'none'
		})
	}
}

onMounted(() => {
	orderId.value = uni.getStorageSync('orderId')
	console.log("orderId:", orderId.value)
	animation.value = uni.createAnimation({
		duration: 150,
		timingFunction: 'ease-out',
	})
	getUserInfo() // Ensure user info is loaded on mount for payment
	
	// 向后端发送购物车菜品ID列表
	sendCartItemsToServer()
	
})

// 页面卸载时清理数据
onUnload(() => {
	orderStore.clearOrderData()
})

// 添加动画相关变量
const popupAnimation = ref(null)
const animation = ref(null)

// 添加新的状态变量
const paymentMethodPopupVisible = ref(false)
const memberCardPopupVisible = ref(false)

// 添加用户信息相关的状态
const userInfo = ref(null)

// 支付选择弹窗
const paymentPopupVisible = ref(false)

// 密码输入弹窗
const password = ref('')
const passwordPopupVisible = ref(false)

// 支付成功弹窗
const successPopupVisible = ref(false)

// 数字键盘布局
const keyboardRows = [
  ['1', '2', '3'],
  ['4', '5', '6'],
  ['7', '8', '9'],
  ['', '0', 'del']
]

// 支付弹窗状态变化
const paymentPopupChange = (e) => {
  if (!e.show) {
    paymentPopupVisible.value = false
  }
}

// 密码弹窗状态变化
const payPasswordPopupChange = (e) => {
  if (!e.show) {
    passwordPopupVisible.value = false
    password.value = ''
    // 如果不是要显示成功弹窗，则显示原生 tabBar
    if (!successPopupVisible.value) {
      // uni.showTabBar() - 移除，非tabBar页面
    }
  }
}

// 添加一个检查弹窗状态的方法
const checkPopupStatus = () => {
  // 移除tabBar操作，payment页面不是tabBar页面
  // 如果有任何一个弹窗显示，就隐藏 tabBar
  if (paymentMethodPopupVisible.value || 
      paymentPopupVisible.value || 
      passwordPopupVisible.value || 
      memberCardPopupVisible.value || 
      successPopupVisible.value) {
    // uni.hideTabBar() - 移除，非tabBar页面
  } else {
    // 所有弹窗都关闭时，显示 tabBar
    // uni.showTabBar() - 移除，非tabBar页面
  }
}

// 关闭支付弹窗
const closePaymentPopup = () => {
  // 执行滑出动画
  animation.value.translateY('100%').step()
  popupAnimation.value = animation.value.export()
  // 延迟关闭弹窗
  setTimeout(() => {
    paymentPopupVisible.value = false
    checkPopupStatus()
  }, 200)
}

// 关闭密码弹窗
const closePayPasswordPopup = () => {
  // 执行滑出动画
  animation.value.translateY('100%').step()
  popupAnimation.value = animation.value.export()
  // 延迟关闭弹窗
  setTimeout(() => {
    passwordPopupVisible.value = false
    password.value = ''  // 清空密码输入框
    checkPopupStatus()
  }, 200)
}

// 关闭成功弹窗
const closePaySuccessPopup = () => {
  successPopupVisible.value = false;
  uni.switchTab({ url: '/src/pages/order/index' });
}

// 处理键盘输入
const onKeyClick = (key) => {
  if (key === 'del') {
    if (password.value.length > 0) {
      password.value = password.value.slice(0, -1)
    }
  } else if (key && password.value.length < 6) {
    password.value += key
    if (password.value.length === 6) {
      verifyPassword()
    }
  }
}

// 验证密码（微信支付）
const verifyPassword = async () => {
  try {
    if (!userInfo.value) {
      throw new Error('请先登录')
    }

    // 创建订单
    const orderData = {
      totalAmount: totalAmount.value,
      discountAmount: selectedCoupon.value?.amount || 0,
      payableAmount: finalAmount.value,
      orderType: 2, // 默认为外卖订单
      remark: orderRemark.value || "",
      shippingAddress: orderInfo.value.mode === 'takeout' ? 
        `${selectedAddress.value?.province}${selectedAddress.value?.city}${selectedAddress.value?.district}${selectedAddress.value?.street}${selectedAddress.value?.detail}` : "",
      uId: userInfo.value.uId
    }
    
    console.log("创建订单数据:", orderData)
    const orderRes = await orderApi.createOrder(orderData)
    
    if (orderRes.code !== 200 || !orderRes.data) {
      throw new Error(orderRes.msg || '创建订单失败')
    }
    
    // 保存订单编号到本地存储
    uni.setStorageSync('orderId', orderRes.data)
    const orderId = orderRes.data; // 直接用接口返回的订单号
    
    // 构建支付记录数据
    const payHistory = {
      order_id: Number(orderId),  // 用刚刚返回的orderId
      u_id: Number(userInfo.value.uId),  // 确保是数字类型
      pay_amount: Number(finalAmount.value),  // 确保是数字类型
      pay_way: Number(0),  // 确保是数字类型，0表示微信支付
      pay_time: new Date().toISOString()  // 添加支付时间
    }
    
    console.log('支付记录数据:', payHistory)
    
    // 发送添加支付记录请求
    const token = uni.getStorageSync('token')
    const res = await payHistoryApi.addPayHistory(token, payHistory)
    
    if (res.code !== 200) {
      throw new Error(res.msg || '支付失败')
    }

    // 新增：批量添加订单菜品项
    try {
      const items = cartItems.value.map(item => ({
        orderId: Number(orderId), // 用后端返回的新主键ID
        dishId: Number(item.dishId),
        quantity: Number(item.quantity)
      }))
      const addItemsRes = await payHistoryApi.addOrderItems(token, items)
      if (addItemsRes.code !== 200) {
        throw new Error(addItemsRes.msg || '订单菜品项添加失败')
      }
    } catch (err) {
      console.error('添加订单菜品项失败:', err)
      uni.showToast({
        title: err.message || '订单菜品项添加失败',
        icon: 'none'
      })
    }

    // 新增：如果使用了优惠券，调用优惠券扣除接口
    if (selectedCoupon.value && selectedCoupon.value.id) {
      console.log('会员卡支付 - 准备扣除优惠券，优惠券信息：', selectedCoupon.value);
      console.log('用户信息：', userInfo.value);

      try {
        console.log('会员卡支付 - 使用 uId 获取 customerId, uId: ', userInfo.value.uId);
        const customerIdRes = await customerApi.useCusIdFindUId(userInfo.value.uId);
        if (customerIdRes.code !== 200 || !customerIdRes.data) {
          throw new Error(`获取 customerId 失败: ${customerIdRes.msg || '无有效数据'}`);
        }
        const customerId = customerIdRes.data;
        console.log('会员卡支付 - 成功获取 customerId:', customerId);

        console.log('会员卡支付 - 使用获取到的 customerId 调用 useCoupon:', customerId);
        const couponRes = await couponApi.useCoupon(customerId, selectedCoupon.value.id);
        console.log('会员卡支付 - 优惠券扣除成功：', couponRes);
      } catch (err) {
        console.error('会员卡支付 - 优惠券扣除流程失败：', err);
        uni.showToast({
          title: err.message || '优惠券使用失败',
          icon: 'none'
        });
      }
    }
    
    // 调用确认库存接口
    try {
      const confirmRes = await orderApi.confirmInventory(orderId);
      console.log('库存确认成功:', confirmRes);
    } catch (err) {
      console.error('库存确认失败:', err);
    }

    // 支付成功
    uni.showToast({
      title: '支付成功',
      icon: 'success',
      duration: 1200
    })
    // 显示支付成功弹窗
    successPopupVisible.value = true;
    
    // 支付成功后返回上一页
    setTimeout(() => {
      uni.navigateBack()
    }, 2000)

  } catch (error) {
    uni.showToast({ 
      title: error.message || '支付失败，请稍后重试', 
      icon: 'none',
      duration: 2000
    })
    if (error.message === '请先登录') {
      setTimeout(() => {
        uni.navigateTo({
          url: '/pages/login/index'
        })
      }, 1500)
    }
  }
}

// 支付弹窗内点击支付，弹出密码输入弹窗
const confirmPayment = () => {
  // 先隐藏原生 tabBar
  // uni.hideTabBar() - 移除，非tabBar页面
  closePaymentPopup()
  passwordPopupVisible.value = true
  // 执行滑入动画
  nextTick(() => {
    animation.value.translateY(0).step()
    popupAnimation.value = animation.value.export()
    checkPopupStatus()
  })
}

// Renamed from payOrder to avoid conflict and reflect purpose in payment.vue
const initiatePaymentProcess = () => {
  // Setting current order is not directly needed, use orderInfo.value instead
  // currentOrder.value = orderInfo.value
  
  if(orderInfo.value.mode === 'scan'){
	scanOrderCreate()
  }else{
	// Display payment method selection popup
	paymentMethodPopupVisible.value = true
	// Execute slide-in animation
	nextTick(() => {
		animation.value.translateY(0).step()
		popupAnimation.value = animation.value.export()
		checkPopupStatus()
	})
  }
  
}

// 关闭支付方式选择弹窗
const closePaymentMethodPopup = () => {
  // 执行滑出动画
  animation.value.translateY('100%').step()
  popupAnimation.value = animation.value.export()
  // 延迟关闭弹窗
  setTimeout(() => {
    paymentMethodPopupVisible.value = false
    checkPopupStatus()
  }, 200)
}

// 选择支付方式
const selectPaymentMethod = (method) => {
  closePaymentMethodPopup()
  if (method === 'wechat') {
    // 显示支付选择弹窗
    paymentPopupVisible.value = true
    // 执行滑入动画
    nextTick(() => {
      animation.value.translateY(0).step()
      popupAnimation.value = animation.value.export()
      checkPopupStatus()
    })
  } else if (method === 'member') {
    // 显示会员卡支付确认弹窗
    memberCardPopupVisible.value = true
    // 执行滑入动画
    nextTick(() => {
      animation.value.translateY(0).step()
      popupAnimation.value = animation.value.export()
      checkPopupStatus()
    })
  }
}

// 关闭会员卡支付提示弹窗
const closeMemberCardPopup = () => {
  // 执行滑出动画
  animation.value.translateY('100%').step()
  popupAnimation.value = animation.value.export()
  // 延迟关闭弹窗
  setTimeout(() => {
    memberCardPopupVisible.value = false
    checkPopupStatus()
  }, 200)
}

// 确认会员卡支付
const confirmMemberCardPayment = () => {
  closeMemberCardPopup()
  handleMemberCardPayment()
}

// 处理会员卡支付
const handleMemberCardPayment = async () => {
  try {
    if (!userInfo.value) {
      throw new Error('请先登录')
    }

    // 创建订单
    const orderData = {
      totalAmount: totalAmount.value,
      discountAmount: selectedCoupon.value?.amount || 0,
      payableAmount: finalAmount.value,
      orderType: 2, // 默认为外卖订单
      remark: orderRemark.value || "",
      shippingAddress: orderInfo.value.mode === 'takeout' ? 
        `${selectedAddress.value?.province}${selectedAddress.value?.city}${selectedAddress.value?.district}${selectedAddress.value?.street}${selectedAddress.value?.detail}` : "",
      uId: userInfo.value.uId
    }
    
    console.log("创建订单数据:", orderData)
    const orderRes = await orderApi.createOrder(orderData)
    
    if (orderRes.code !== 200 || !orderRes.data) {
      throw new Error(orderRes.msg || '创建订单失败')
    }
    
    // 保存订单编号到本地存储
    uni.setStorageSync('orderId', orderRes.data)
    const orderId = orderRes.data; // 直接用接口返回的订单号
    
    // 构建支付记录数据
    const payHistory = {
      order_id: Number(orderId),  // 用刚刚返回的orderId
      u_id: Number(userInfo.value.uId),  // 确保是数字类型
      pay_amount: Number(finalAmount.value),  // 确保是数字类型
      pay_way: Number(1),  // 确保是数字类型，1表示会员卡支付
      pay_time: new Date().toISOString()  // 添加支付时间
    }
    
    console.log('支付记录数据:', payHistory)
    
    // 发送添加支付记录请求
    const token = uni.getStorageSync('token')
    const res = await payHistoryApi.addPayHistory(token, payHistory)
    
    if (res.code !== 200) {
      throw new Error(res.msg || '支付失败')
    }

    // 新增：批量添加订单菜品项
    try {
      const items = cartItems.value.map(item => ({
        orderId: Number(orderId), // 用后端返回的新主键ID
        dishId: Number(item.dishId),
        quantity: Number(item.quantity)
      }))
      const addItemsRes = await payHistoryApi.addOrderItems(token, items)
      if (addItemsRes.code !== 200) {
        throw new Error(addItemsRes.msg || '订单菜品项添加失败')
      }
    } catch (err) {
      uni.showToast({
        title: err.message || '订单菜品项添加失败',
        icon: 'none'
      })
    }

    // 新增：如果使用了优惠券，调用优惠券扣除接口
    if (selectedCoupon.value && selectedCoupon.value.id) {
      console.log('会员卡支付 - 准备扣除优惠券，优惠券信息：', selectedCoupon.value);
      console.log('用户信息：', userInfo.value);

      try {
        console.log('会员卡支付 - 使用 uId 获取 customerId, uId: ', userInfo.value.uId);
        const customerIdRes = await customerApi.useCusIdFindUId(userInfo.value.uId);
        if (customerIdRes.code !== 200 || !customerIdRes.data) {
          throw new Error(`获取 customerId 失败: ${customerIdRes.msg || '无有效数据'}`);
        }
        const customerId = customerIdRes.data;
        console.log('会员卡支付 - 成功获取 customerId:', customerId);

        console.log('会员卡支付 - 使用获取到的 customerId 调用 useCoupon:', customerId);
        const couponRes = await couponApi.useCoupon(customerId, selectedCoupon.value.id);
        console.log('会员卡支付 - 优惠券扣除成功：', couponRes);
      } catch (err) {
        console.error('会员卡支付 - 优惠券扣除流程失败：', err);
        uni.showToast({
          title: err.message || '优惠券使用失败',
          icon: 'none'
        });
      }
    }
    
    // 调用确认库存接口
    try {
      const confirmRes = await orderApi.confirmInventory(orderId);
      console.log('库存确认成功:', confirmRes);
    } catch (err) {
      console.error('库存确认失败:', err);
    }

    // 支付成功
    uni.showToast({
      title: '支付成功',
      icon: 'success',
      duration: 1200
    })
    
    // 支付成功后返回上一页
    setTimeout(() => {
      uni.navigateBack()
    }, 2000)

  } catch (error) {
    uni.showToast({ 
      title: error.message || '支付失败，请稍后重试', 
      icon: 'none',
      duration: 2000
    })
    if (error.message === '请先登录') {
      setTimeout(() => {
        uni.navigateTo({
          url: '/pages/login/index'
        })
      }, 1500)
    }
  }
}

const scanOrderCreate = async () => {
	const token = uni.getStorageSync('token')
	const orderId = uni.getStorageSync('orderId')
	const order = {
		orderId : orderId || null,
		boardId: orderInfo.value.board.boardId || null,
		totalAmount: totalAmount.value,
		discountAmount: selectedCoupon.value?.amount || 0,
		payableAmount: finalAmount.value,
		orderType: 1,
		remark: orderRemark.value || "",
		uId:token
	}
	const orderItems = cartItems.value.map(item => ({
		dishId: item.dishId,
		quantity: item.quantity
	}))
	const orderDTO = {
		order : order,
		orderItems : orderItems,
		couponId : selectedCoupon.value?.id || 0
	}
	console.log("orderDTO:",orderDTO);

	console.log("orderDTO:",orderDTO)
	const orderRes = await orderApi.insertOrder(orderDTO)
	console.log("orderRes:",orderRes)
	uni.setStorageSync('orderId', orderRes.data)
	if(orderRes.code !== 200){
		uni.showToast({
			title: orderRes.msg || '创建订单失败',
			icon: 'none'
		})
		return
	}else{
		uni.showToast({
			title: '创建订单成功',
			icon: 'success'
		})
		// 订单创建成功后返回上一页
		setTimeout(() => {
			uni.navigateBack()
		}, 1500)
	}
}

// Add user info retrieval method
const getUserInfo = () => {
  try {
    // Retrieve user info directly from local storage
    const storedUserInfo = uni.getStorageSync('userInfo')
    if (!storedUserInfo) {
      throw new Error('请先登录')
    }
    userInfo.value = storedUserInfo
  } catch (error) {
    uni.showToast({
      title: error.message || 'Failed to get user info',
      icon: 'none'
    })
    // Navigate to login page if login error
    setTimeout(() => {
      uni.navigateTo({
        url: '/pages/login/index'
      })
    }, 1500)
  }
}

// 向后端发送购物车菜品ID列表
const sendCartItemsToServer = () => {
	try {
		// 从购物车中提取菜品ID
		const dishIds = cartItems.value.map(item => item.dishId)
		
		console.log('发送购物车菜品ID列表:', dishIds)

		// 生成订单编号（建议用时间戳或 uuid）
		const orderId = Date.now(); // 或从后端获取订单编号

		// 调用API检查菜品可用性
		if (dishIds.length > 0) {

			const requestBody = {
				orderId: orderId,
				dishIdList: dishIds
			};

			dishApi.checkDishAvailability(requestBody).then(res => {
				console.log('菜品可用性检查结果:', res)
				
				// 检查是否有不可用的菜品
				if (res && res.data && res.data.cannotMakeDishNames && res.data.cannotMakeDishNames.length > 0) {
					// 显示不可用菜品提示
					const unavailableDishNames = res.data.cannotMakeDishNames.join('、');
					
					uni.showModal({
						title: '菜品已售罄提示',
						content: `很抱歉，以下菜品暂时无法提供：${unavailableDishNames}，请返回重新选择`,
						showCancel: false,
						success: () => {
							// 直接返回上一页
							uni.navigateBack();
						}
					});
				}
			}).catch(err => {
				console.error('菜品可用性检查失败:', err)
				// 添加用户友好的错误处理
				uni.showToast({
					title: '菜品状态检查失败，请稍后再试',
					icon: 'none'
				})
			})
			
		}
	} catch (error) {
		console.error('发送购物车菜品ID失败:', error)
	}
}

// 格式化金额为两位小数
const formatAmount = (amount) => {
	if (amount === null || amount === undefined) return '0.00'
	return Number(amount).toFixed(2)
}
</script>

<style lang="scss" scoped>
.payment-container {
	min-height: 100vh;
	background: #f8f9fa;
	padding-bottom: 100px;
}

.order-info-section {
	background: #fff;
	padding: 20px 16px;
	margin-bottom: 12px;
	border-radius: 0 0 16px 16px;
	box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.store-info {
	display: flex;
	align-items: center;
	gap: 8px;
}

.store-icon {
	width: 20px;
	height: 20px;
}

.store-name {
	font-size: 16px;
	font-weight: 600;
	color: #333;
}

.store-address {
	font-size: 13px;
	color: #666;
	margin-top: 4px;
}

.delivery-address {
	margin-top: 16px;
	padding-top: 16px;
	border-top: 1px solid #f0f0f0;
}

.address-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 12px;
}

.address-title {
	font-size: 16px;
	font-weight: 600;
	color: #333;
}

.change-address {
	color: #008CB5;
	font-size: 14px;
}

.address-content {
	background: #f8f9fa;
	padding: 16px;
	border-radius: 12px;
}

.contact {
	font-size: 15px;
	font-weight: 600;
	color: #333;
	margin-bottom: 8px;
	display: block;
}

.address {
	font-size: 14px;
	color: #666;
	line-height: 1.4;
}

.no-address {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 16px;
	background: #f8f9fa;
	border-radius: 12px;
	color: #999;
}

.section-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 16px;
}

.section-title {
	font-size: 16px;
	font-weight: 600;
	color: #333;
}

.item-count, .coupon-tip, .remark-tip {
	font-size: 13px;
	color: #999;
}

.food-items-section {
	background: #fff;
	padding: 20px 16px;
	margin-bottom: 12px;
	border-radius: 16px;
	box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.food-list {
	.food-item {
		display: flex;
		padding: 16px 0;
		border-bottom: 1px solid #f0f0f0;
		
		&:last-child {
			border-bottom: none;
		}
	}
}

.food-image {
	width: 90px;
	height: 90px;
	border-radius: 12px;
	margin-right: 16px;
	box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.food-info {
	flex: 1;
	display: flex;
	flex-direction: column;
	justify-content: space-between;
}

.food-name {
	font-size: 16px;
	font-weight: 600;
	color: #333;
	margin-bottom: 4px;
}

.food-spec {
	font-size: 13px;
	color: #999;
	margin: 4px 0;
}

.food-remark {
	font-size: 12px;
	color: #999;
	margin-top: 4px;
}

.food-price-quantity {
	display: flex;
	justify-content: space-between;
	align-items: center;
}

.food-price {
	color: #ff6b6b;
	font-weight: 600;
	font-size: 16px;
}

.food-quantity {
	color: #999;
	font-size: 14px;
}

.expand-section {
	display: flex;
	align-items: center;
	justify-content: center;
	padding: 12px 0 0;
	margin-top: 8px;
	border-top: 1px solid #f0f0f0;
	cursor: pointer;
}

.expand-text {
	font-size: 14px;
	color: #666;
	margin-right: 4px;
}

.expand-icon {
	font-size: 14px;
	color: #999;
	transition: transform 0.3s ease;
	
	&.expanded {
		transform: rotate(90deg);
	}
}

.remark-section {
	background: #fff;
	padding: 20px 16px;
	margin-bottom: 12px;
	border-radius: 16px;
	box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.remark-input {
	width: 100%;
	height: 100px;
	background: #f8f9fa;
	border-radius: 12px;
	padding: 16px;
	font-size: 14px;
	color: #333;
}

.amount-section {
	background: #fff;
	padding: 20px 16px;
	// border-radius: 16px;
	// box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.amount-item {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 16px;
	font-size: 14px;
	color: #666;
	
	&.total {
		margin-top: 16px;
		padding-top: 16px;
		border-top: 1px solid #f0f0f0;
		font-size: 16px;
		font-weight: 600;
		color: #333;
	}
}

.discount {
	color: #ff6b6b;
}

.final-amount {
	color: #ff6b6b;
	font-size: 22px;
	font-weight: 600;
}

.payment-footer {
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	background: #fff;
	padding: 12px 16px;
	display: flex;
	justify-content: space-between;
	align-items: center;
	box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);
	height: 64px;
	box-sizing: border-box;
}

.total-info {
	display: flex;
	align-items: baseline;
	gap: 4px;
}

.total-label {
	font-size: 14px;
	color: #666;
}

.price {
	color: #ff6b6b;
	font-size: 24px;
	font-weight: 600;
}

.pay-button {
	background: linear-gradient(135deg, #008CB5 0%, #006688 100%);
	color: #fff;
	border: none;
	border-radius: 28px;
	padding: 0 32px;
	font-size: 16px;
	font-weight: 600;
	height: 44px;
	line-height: 44px;
	min-width: 120px;
	box-shadow: 0 4px 12px rgba(0, 140, 181, 0.2);
	display: flex;
	align-items: center;
	justify-content: center;
	margin: 0;
	
	&:active {
		transform: scale(0.98);
		box-shadow: 0 2px 8px rgba(0, 140, 181, 0.2);
	}
}

.arrow {
	color: #999;
	margin-left: 8px;
}

// 添加加载状态样式
.loading-mask {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background: rgba(255, 255, 255, 0.8);
	display: flex;
	align-items: center;
	justify-content: center;
	z-index: 999;
}

// 添加错误提示样式
.error-tip {
	color: #ff6b6b;
	font-size: 12px;
	margin-top: 4px;
}

.coupon-section {
	background: #fff;
	padding: 20px 16px;
	margin-bottom: 12px;
	border-radius: 16px;
	box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
	cursor: pointer;
}

.selected-coupon {
	margin-top: 8px;
	display: flex;
	justify-content: space-between;
	color: #008CB5;
}

.coupon-popup {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	z-index: 1000;
	display: flex;
	align-items: center;
	justify-content: center;
}

.popup-mask {
	position: absolute;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background: rgba(0,0,0,0.3);
}

.popup-content {
	position: relative;
	background: #fff;
	border-radius: 16px;
	width: 90%;
	max-width: 400px;
	max-height: 80vh;
	z-index: 1001;
	display: flex;
	flex-direction: column;
	padding-bottom: 0;
}

.popup-header {
	position: sticky;
	top: 0;
	background: #fff;
	z-index: 2;
	padding: 20px 0 10px 0;
	text-align: center;
	// border-bottom: 1px solid #f0f0f0;
}

.popup-title {
	font-size: 18px;
	font-weight: 600;
	color: #333;
}

.close-icon {
	position: absolute;
	right: 20px;
	top: 20px;
	font-size: 24px;
	color: #999;
	cursor: pointer;
}

.coupon-list {
	flex: 1;
	overflow-y: auto;
	padding: 16px;
	min-height: 100px;
	max-height: 60vh;
}

.coupon-list::-webkit-scrollbar {
	width: 6px;
}
.coupon-list::-webkit-scrollbar-thumb {
	background: #eee;
	border-radius: 3px;
}

.coupon-item {
	display: flex;
	justify-content: space-between;
	align-items: center;
	background: #fff;
	border-radius: 12px;
	margin-bottom: 16px;
	box-shadow: 0 2px 8px rgba(0,0,0,0.05);
	padding: 16px;
	&.disabled {
		opacity: 0.5;
	}
}

.coupon-info {
	flex: 1;
	display: flex;
	flex-direction: column;
	gap: 4px;
}

.coupon-name {
	font-size: 16px;
	font-weight: 600;
	color: #222;
}

.coupon-desc {
	font-size: 13px;
	color: #666;
}

.coupon-term {
	font-size: 12px;
	color: #bbb;
}

.coupon-action {
	display: flex;
	flex-direction: column;
	align-items: flex-end;
	min-width: 80px;
	margin-left: 16px;
}

.coupon-amount {
	font-size: 20px;
	font-weight: 600;
	color: #008CB5;
	margin-bottom: 8px;
}

.use-btn {
	background: #008CB5;
	color: #fff;
	border: none;
	border-radius: 16px;
	padding: 4px 18px;
	font-size: 14px;
	font-weight: 500;
	cursor: pointer;
	&.btn-disabled {
		background: #c0c0c0;
		color: #fff;
		cursor: not-allowed;
	}
}

.empty-coupon {
	display: flex;
	justify-content: center;
	align-items: center;
	min-height: 200px;
}

.empty-text {
	color: #999;
	font-size: 14px;
}

// 支付弹窗样式
.modal {
	position: fixed;
	top: 0; left: 0; right: 0; bottom: 0;
	z-index: 999;
	
	.modal-mask {
		position: absolute;
		top: 0; left: 0; right: 0; bottom: 0;
		background-color: rgba(0, 0, 0, 0.6);
		backdrop-filter: blur(1px);
	}
	
	.payment-popup-wrapper {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		z-index: 1000;
	}
	
	.payment-popup {
		width: 100%;
		background-color: #ffffff;
		border-top-left-radius: 20rpx;
		border-top-right-radius: 20rpx;
		padding-bottom: constant(safe-area-inset-bottom);
		padding-bottom: env(safe-area-inset-bottom);
		transform: translateY(100%);
	}
}

.payment-popup { /* Popup styles (internal styles) */
	.popup-header { display: flex; justify-content: space-between; align-items: center; padding: 10rpx 30rpx 20rpx; .close-btn { font-size: 40px; color: #999; } .password-btn { font-size: 28rpx; color: #687597; } }
	.amount-section { display: flex; flex-direction: column; justify-content: center; align-items: center; padding: 10rpx 0; .merchant-name { font-size: 28rpx; color: #888; margin-bottom: 20rpx; } .currency-amount-wrapper { display: flex; align-items: flex-end; .currency { font-size: 48rpx; font-weight: bold; color: #333; position: relative; top: -35rpx; } .amount { font-size: 80rpx; font-weight: bold; color: #333; margin-left: 10rpx; } } }
	.divider-line { height: 1rpx; background-color: #eee; margin: 20rpx 0; }
	.payment-method-section { padding: 0 30rpx; margin-bottom: 40rpx; .method-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 20rpx; .label { font-size: 26rpx; color: #999; } .change-method { display: flex; align-items: center; font-size: 26rpx; color: #999; .arrow { margin-left: 10rpx; font-weight: bold; } } } .method-item { display: flex; align-items: center; background: #FFF8E6; border-radius: 12rpx; padding: 40rpx 30rpx; position: relative; .method-icon { width: 25rpx; height: 25rpx; margin-right: 20rpx; position: relative; top: -7px; } .method-details { flex: 1; display: flex; flex-direction: column; justify-content: center; .method-name { font-size: 26rpx; color: #888; margin-bottom: 10px; } .method-provider { font-size: 22rpx; color: #888; } } .checkmark { font-size: 36rpx; color: #07c160; margin-left: 20rpx; position: relative; left: -10px; } } }
	.popup-footer { padding: 20rpx 30rpx; .pay-btn { background-color: #07c160; color: #ffffff; font-size: 32rpx; height: 90rpx; line-height: 90rpx; border-radius: 20rpx; width: 50%; margin-top: 20px; margin-bottom: 20px; } }
}

.pay-password-popup {
	background: #fff;
	border-top-left-radius: 32rpx;
	border-top-right-radius: 32rpx;
	padding-bottom: env(safe-area-inset-bottom);
	box-shadow: 0 -8rpx 32rpx rgba(0,0,0,0.08);
	position: fixed;
	bottom: -33px;
  width: 100%;
	.popup-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 15rpx 32rpx 0 32rpx;
		.close-btn {
			font-size: 40px;
			color: #333;
		}
		.face-btn {
			font-size: 28rpx;
			color: #576b95;
		}
	}
	.popup-amount {
		display: flex;
		flex-direction: column;
		align-items: center;
		margin-top: 16rpx;
		.merchant {
			font-size: 28rpx;
			color: #888;
			margin-bottom: 8rpx;
		}
		.currency-amount-row {
			display: flex;
			align-items: baseline;
			justify-content: center;
			.currency {
				font-size: 22px;
				font-weight: 600;
				color: #222;
				margin-right: 2px;
				position: relative;
				top: -2px;
			}
			.amount {
				font-size: 40px;
				font-weight: 600;
				color: #222;
				line-height: 1;
			}
		}
	}
	.popup-method {
		margin: 0 32rpx 24rpx 32rpx;
		.method-label {
			font-size: 24rpx;
			color: #999;
			margin-bottom: 8rpx;
		}
		.method-change {
			position: absolute;
			right: 48rpx;
			top: 0;
			font-size: 24rpx;
			color: #999;
			.arrow { margin-left: 4rpx; }
		}
		.method-item {
			display: flex;
			align-items: center;
			background: #EAF3FC;
			border-radius: 16rpx;
			padding: 37rpx 20rpx;
			margin-top: 25rpx;
			.method-icon {
				width: 50rpx;
				height: 40rpx;
				margin-right: 16rpx;
			}
			.method-info {
				flex: 1;
				display: flex;
				flex-direction: column;
				.method-name {
					font-size: 28rpx;
					color: #333;
				}
				.method-desc {
					font-size: 22rpx;
					color: #888;
				}
			}
			.checkmark {
				font-size: 36rpx;
				color: #07c160;
				margin-left: 12rpx;
			}
		}
		position: relative;
	}
	.popup-password {
		display: flex;
		justify-content: center;
		align-items: center;
		margin: 32rpx 0 0 0;
		.password-box {
			display: flex;
			gap: 16rpx;
			.pwd-cell {
				width: 74rpx;
				height: 74rpx;
				border-radius: 8rpx;
				background: #F2F2F2;
				display: flex;
				align-items: center;
				justify-content: center;
				margin: 10px 0px;
				.dot {
					width: 16rpx;
					height: 16rpx;
					background: #222;
					border-radius: 50%;
				}
			}
		}
	}
	.popup-keyboard {
		background: #EDEDED;
		padding-bottom: env(safe-area-inset-bottom);
		margin-top: 10px;
		border-top: 1px solid #EDEDED;
		.keyboard-row {
			display: flex;
			width: 100%;
			.key-btn {
				flex: 1;
				height: 55px;
				background: #fff;
				display: flex;
				align-items: center;
				justify-content: center;
				font-size: 28px;
				color: #222;
				border-right: 1px solid #e5e5e5;
				border-bottom: 1px solid #e5e5e5;
				box-sizing: border-box;
				border-radius: 0;
				&.del {
					background: #EDEDED;
					color: #222;
				}
				&.empty {
					background: #EDEDED;
					border-right: none;
					border-bottom: none;
				}
			}
			.key-btn:last-child {
				border-right: none;
			}
		}
		.keyboard-row:last-child .key-btn {
			border-bottom: none;
		}
	}
}

.pay-success-popup {
	position: fixed;
	left: 0; right: 0; top: 0; bottom: 0;
	width: 100vw; height: 100vh;
	background: #fff;
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: flex-start;
	z-index: 9999;
	.success-top-bar {
		margin-top: 25px;
		margin-bottom: 50px;
		display: flex;
		flex-direction: row;
		align-items: center;
		justify-content: center;
		.success-icon {
			width: 20px;
			height: 20px;
			margin-bottom: 0;
		}
		.success-text {
			color: #07c160;
			font-size: 15px;
			font-weight: 500;
			margin-left: 8px;
			margin-bottom: 0;
		}
	}
	.success-amount-block {
		margin-top: 16px;
		display: flex;
		flex-direction: column;
		align-items: center;
		.success-merchant {
			color: #888;
			font-size: 15px;
			margin-bottom: 10px;
		}
		.success-amount-row {
				display: flex;
				align-items: baseline;
				justify-content: center;
				.currency {
					font-size: 30px;
					font-weight: 600;
					color: #222;
					margin-right: 2px;
					position: relative;
					top: -9px;
				}
				.amount {
					font-size: 40px;
					font-weight: 600;
					color: #222;
					line-height: 1;
				}
			}
		}
	.success-progress {
		width: 80vw;
		margin: 32px 0 48px 0;
		display: flex;
		justify-content: center;
		.progress-bar {
			width: 100%;
			height: 6px;
			background: #f5f5f5;
			border-radius: 3px;
			overflow: hidden;
			.progress-inner {
				width: 30px;
				height: 100%;
				background: #fa5151;
				border-radius: 3px;
			}
		}
	}
	.success-bottom-block {
		width: 100vw;
		display: flex;
		flex-direction: column;
		align-items: center;
		position: absolute;
		bottom: 60px;
		left: 0;
		.success-btn {
			position: relative;
			top: -40px;
			width: 40vw;
			height: 44px;
			background: #f5f5f5;
			color: #222;
			font-size: 15px;
			border-radius: 5px;
			border: none;
			margin: 0 auto;
			text-align: center;
			line-height: 44px;
		}
	}
}

.payment-method-popup {
  width: 100%;
  background: #fff;
  border-top-left-radius: 32rpx;
  border-top-right-radius: 32rpx;
  padding-bottom: env(safe-area-inset-bottom);
  box-shadow: 0 -8rpx 32rpx rgba(0,0,0,0.08);
  transform: translateY(100%);

  .popup-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 32rpx;
    .close-btn {
      font-size: 40px;
      color: #333;
    }
    .title {
      font-size: 32rpx;
      font-weight: 500;
      color: #333;
    }
  }

  .method-list {
    padding: 0 32rpx;
    .method-item {
      display: flex;
      align-items: center;
      padding: 32rpx 0;
      border-bottom: 1px solid #f5f5f5;
      &:last-child {
        border-bottom: none;
      }
      .method-icon {
        width: 40rpx;
        height: 40rpx;
        margin-right: 24rpx;
        &.wechat-icon {
          width: 44rpx;
          height: 44rpx;
        }
        &.member-icon {
          width: 48rpx;
          height: 48rpx;
        }
      }
      .method-info {
        flex: 1;
        .method-name {
          font-size: 28rpx;
          color: #333;
          margin-bottom: 8rpx;
        }
        .method-desc {
          font-size: 24rpx;
          color: #999;
        }
      }
      .checkmark {
        font-size: 36rpx;
        color: #07c160;
        margin-left: 24rpx;
      }
    }
  }
}

.member-card-popup {
  width: 100%;
  background: #fff;
  border-top-left-radius: 32rpx;
  border-top-right-radius: 32rpx;
  padding-bottom: env(safe-area-inset-bottom);
  box-shadow: 0 -8rpx 32rpx rgba(0,0,0,0.08);
  transform: translateY(100%);

  .popup-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 32rpx;
    .close-btn {
      font-size: 40px;
      color: #333;
    }
    .title {
      font-size: 32rpx;
      font-weight: 500;
      color: #333;
    }
  }

  .popup-content {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 48rpx 32rpx;
    .card-icon {
      width: 96rpx;
      height: 96rpx;
      margin-bottom: 32rpx;
    }
    .amount-info {
      display: flex;
      flex-direction: column;
      align-items: center;
      margin-bottom: 32rpx;
      .amount-label {
        font-size: 28rpx;
        color: #999;
        margin-bottom: 16rpx;
      }
      .amount-row {
        display: flex;
        align-items: baseline;
        .currency {
          font-size: 32rpx;
          font-weight: 600;
          color: #333;
          margin-right: 4rpx;
          position: relative;
          top: -4rpx;
        }
        .amount {
          font-size: 48rpx;
          font-weight: 600;
          color: #333;
        }
      }
    }
    .tip-text {
      font-size: 32rpx;
      color: #333;
      margin-bottom: 16rpx;
    }
    .sub-tip {
      font-size: 28rpx;
      color: #999;
    }
  }

  .popup-footer {
    padding: 32rpx;
    .confirm-btn {
      width: 100%;
      height: 88rpx;
      line-height: 88rpx;
      background: #07c160;
      color: #fff;
      font-size: 32rpx;
      border-radius: 44rpx;
      border: none;
    }
  }
}
</style>
